define(['jquery', 'bootstrap', 'backend', 'table', 'form'], function ($, undefined, Backend, Table, Form) {

    var newhouse_id = Fast.api.query('newhouse_id');
    var Controller = {
        index: function () {
            // 初始化表格参数配置
            Table.api.init({
                extend: {
                    index_url: 'newhouse/realscene/index' + location.search,
                    add_url: 'newhouse/realscene/add/newhouse_id/' + + newhouse_id,
                    edit_url: 'newhouse/realscene/edit/newhouse_id/' + + newhouse_id,
                    del_url: 'newhouse/realscene/del',
                    multi_url: 'newhouse/realscene/multi',
                    table: 'newhouse_realscene',
                }
            });

            var table = $("#table");

            // 初始化表格
            table.bootstrapTable({
                url: $.fn.bootstrapTable.defaults.extend.index_url,
                pk: 'id',
                sortName: 'id',
                queryParams: function (params) {
                    var filter = params.filter ? JSON.parse(params.filter) : {};
                    if (newhouse_id) {
                        filter['newhouse_id'] = newhouse_id;
                    }
                    params.filter = JSON.stringify(filter);
                    return params;
                },
                columns: [
                    [
                        {checkbox: true},
                        {field: 'id', title: __('Id')},
                        {field: 'newhouse.title', title: __('Newhouse.title')},
                        {field: 'category', title: __('Category'), searchList: {"1":__('Category 1'),"2":__('Category 2'),"3":__('Category 3'),"4":__('Category 4'), '6':__('Category 6')}, formatter: Table.api.formatter.normal},
                        {field: 'title', title: __('Title')},
                        {field: 'image', title: __('Image'), operate: false, formatter: Table.api.formatter.images, events: Table.api.events.image},
                        {field: 'flag', title: __('Flag'), searchList: {"0":__('Flag 0'),"1":__('Flag 1')}, formatter: Controller.api.formatter.flag},
                        {field: 'createtime', title: __('Createtime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'updatetime', title: __('Updatetime'), operate:'RANGE', addclass:'datetimerange', formatter: Table.api.formatter.datetime},
                        {field: 'admin.nickname', title: __('Admin.nickname')},
                        {field: 'operate', title: __('Operate'), table: table, buttons: [
                                {
                                    name: 'lb',
                                    text: '列表',
                                    icon: 'fa fa-image',
                                    classname: 'btn btn-xs btn-warning btn-addtabs',
                                    url: function (row, column) {
                                        return "newhouse/realscenelist?realscene_id=" + row.id;
                                    }
                                }], events: Table.api.events.operate, formatter: Table.api.formatter.operate}
                    ]
                ]
            });

            // 为表格绑定事件
            Table.api.bindevent(table);
        },
        add: function () {
            Controller.api.bindevent();

            // 一进页面就必须初始化一次
            // 普通模式可以不需要
            // if(type == 0){
            //     $('.arealist-class').attr('style','display:block;')
            //     $('.newhouse-class').attr('style','display:none;')
            // }else if(type == 1){
            //     $('.newhouse-class').attr('style','display:block;')
            //     $('.arealist-class').attr('style','display:none;')
            // }
            $('#c-category').change(function(){
                // var type = $('#c-category').val()
                // console.log(type)
                var type = $(this).val()
                if(type == 1){
                    $('.layout-class').attr('style','display: block;')
                    $('.title-class').attr('style','display: none;')
                    $('.classify-class').attr('style','display: none;')
                }else if(type == 2 || type == 4 || type == 6){
                    switch (type) {
                        case '2':
                            $('#c-title').attr('placeholder', '例如：营销中心、小区环境等。（限制20字内）')
                            break;
                        case '4':
                            $('#c-title').attr('placeholder', '例如：2020年8月30日2.1期开盘。（限制20字内）')
                            break;
                        case '6':
                            $('#c-title').attr('placeholder', '例如：2020年3月20日 3栋封顶。（限制20字内）')
                            break;
                    }
                    $('.layout-class').attr('style','display: none;')
                    $('.title-class').attr('style','display: block;')
                    $('.classify-class').attr('style','display: none;')
                }else if(type == 3){
                    $('.layout-class').attr('style','display: none;')
                    $('.title-class').attr('style','display: none;')
                    $('.classify-class').attr('style','display: block;')
                }
            })
        },
        edit: function () {
            Controller.api.bindevent();
            // 初始化修改
            var type = $('#c-category').val()
            if(type == 1){
                $('.layout-class').attr('style','display: block;')
                $('.title-class').attr('style','display: none;')
                $('.classify-class').attr('style','display: none;')
            }else if(type == 2 || type == 4 || type == 6){
                $('.layout-class').attr('style','display: none;')
                $('.title-class').attr('style','display: block;')
                $('.classify-class').attr('style','display: none;')
            }else if(type == 3){
                $('.layout-class').attr('style','display: none;')
                $('.title-class').attr('style','display: none;')
                $('.classify-class').attr('style','display: block;')
            }
            // 改变值时修改
            $('#c-category').change(function(){
                var type = $(this).val()
                if(type == 1){
                    $('.layout-class').attr('style','display: block;')
                    $('.title-class').attr('style','display: none;')
                    $('.classify-class').attr('style','display: none;')
                }else if(type == 2 || type == 4 || type == 6){
                    switch (type) {
                        case '2':
                            $('#c-title').attr('placeholder', '例如：营销中心、小区环境等。（限制20字内）')
                            break;
                        case '4':
                            $('#c-title').attr('placeholder', '例如：2020年8月30日2.1期开盘。（限制20字内）')
                            break;
                        case '6':
                            $('#c-title').attr('placeholder', '例如：2020年3月20日 3栋封顶。（限制20字内）')
                            break;
                    }
                    $('.layout-class').attr('style','display: none;')
                    $('.title-class').attr('style','display: block;')
                    $('.classify-class').attr('style','display: none;')
                }else if(type == 3){
                    $('.layout-class').attr('style','display: none;')
                    $('.title-class').attr('style','display: none;')
                    $('.classify-class').attr('style','display: block;')
                }
            })
        },
        api: {
            bindevent: function () {
                $("#c-structure_id").data("params", function (obj) {
                    return {custom: {newhouse_id: newhouse_id}};
                });
                $("#c-layout_id").data("params", function (obj) {
                    return {custom: {structure_id: $("#c-structure_id").val()}};
                });
                $("#c-structure_id").change(function () {
                    $("#c-layout_id").selectPageClear();
                });

                Form.api.bindevent($("form[role=form]"));

                var image_input = $('#plupload-image').data("input-id") ? $('#plupload-image').data("input-id") : ""; // c-image
                var image_preview = $('#plupload-image').data("preview-id") ? $('#plupload-image').data("preview-id") : ""; // p-image
                if (image_preview) {
                    // 移除按钮事件
                    $(document.body).off("click", "#" + image_preview + " .btn-trash");
                    // 监听事件
                    // $("#plupload-image").data("upload-success", function(data, ret) {
                    //     //这里进行后续操作
                    //     $(this).hide();

                    // });
                    $(document.body).on("click", "#" + image_preview + " .btn-trash", function () {
                        var that = $(this);
                        // var path = $("#" + image_preview + " [data-url]");
                        // 改成选择当前a标签的上一个元素获取path
                        var lis = that.siblings()
                        var imgPath = lis.eq(0).attr('data-url')
                        // var imgMsgPath = that.prev().attr('value')
                        // var imgMsgName = that.prev().attr('name')
                        // var imgMsgIndex = imgMsgName.substr(-2, 1)
                        Layer.confirm('是否删除该图片？（删除后不可恢复）',
                            {icon: 3, title: __('Warning'), offset: 0, shadeClose: true},
                            function (index) {
                                var options = {
                                    url: 'newhouse/realscene/delUpload',
                                    data: {
                                        path: imgPath
                                    }
                                }
                                Fast.api.ajax(options, function () {
                                    // 多图片单张删除组合完显示
                                    // console.log(imgMsg)
                                    if (image_input) {
                                        // 获取图片集Value值
                                        var images = $("#" + image_input).val()
                                        // 根据 , 号进行分割数组
                                        var imagesArr = images.split(',')
                                        var imageKey = $.inArray(imgPath, imagesArr)
                                        // 删除索引的数组 冲imageKey索引开始，值删除一个值
                                        imagesArr.splice(imageKey, 1)
                                        // 重新将数组组合成字符串
                                        var newImagesString = imagesArr.toString()
                                        // 传入input的 value值中
                                        $("#" + image_input).val(newImagesString)

                                        // 处理图片描述
                                        // var imgMsg = $("textarea[name='row[msg]']").val();
                                        // var imgMsgLength = imgMsg.length
                                        // imgMsg = imgMsg.substr(1,imgMsgLength-2);
                                        // var imgMsgArr = imgMsg.split(',')
                                        // console.log(imgMsgArr)
                                        // imgMsgArr.splice(imgMsgIndex, 1)
                                        // console.log(imgMsgIndex)
                                        // console.log(imgMsgArr)
                                        // if (imgMsgArr.length) {
                                        //     var newImgMsgString = '[' + imgMsgArr.toString() + ']'
                                        // }else{
                                        //     var newImgMsgString = ''
                                        // }
                                        // $("textarea[name='row[msg]']").val(newImgMsgString)
                                        that.closest("li").remove();
                                        var imageLi = $('#p-image li')
                                        var fullImgMsg = '';
                                        for (var i = 0; i < imageLi.length; i++) {
                                            if(imageLi.length > 1 && i < imageLi.length-1){
                                                fullImgMsg += '"' + $(imageLi[i]).children('input').attr('value') + '",'
                                            }else{
                                                fullImgMsg += '"' + $(imageLi[i]).children('input').attr('value') + '"'
                                            }
                                        }
                                        var imgMsgString = '[' + fullImgMsg + ']'
                                        $("textarea[name='row[msg]']").val(imgMsgString)
                                        Layer.close(index);
                                    }
                                });
                            }
                        );
                    });
                }
                // if ($("#" + image_input).val() != '') {
                //     $("#" + image_input).hide();
                // }
            },
            formatter: {
                image: function (value, row, index) {
                    value = value ? Fast.api.cdnurl(value) : '/assets/img/blank.gif';
                    var classname = typeof this.classname !== 'undefined' ? this.classname : 'img-sm img-center';
                    return '<a href="javascript:void(0);"><img class="' + classname + '" src="' + value + '" /></a>';
                },
                flag: function (value, row, index) {
                    return '<a class="btn-change text-success" data-url="'+$.fn.bootstrapTable.defaults.extend.multi_url+'" data-id="' + row.id + '" data-params="flag=' + (row.flag == '0' ? '1' : '0') + '"><i class="fa ' + (row.flag == '0' ? 'fa-toggle-off' : 'fa-toggle-on') + ' fa-2x"></i></a>';
                }
            }
        }
    };
    return Controller;
});
